package com.example.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.commonsutils.R;
import com.example.common.exception.GuliException;
import com.example.eduservice.entity.EduVideo;
import com.example.eduservice.mapper.EduVideoMapper;
import com.example.eduservice.service.EduVideoService;
import com.example.eduservice.service.FeignService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @Author:tjf
 * @Description:
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
    @Resource
    private EduVideoMapper videoMapper;
    @Resource
    private FeignService feignService;
    /**
     * 根据课程id，删除小节信息
     * @param courseId
     */
    @Override
    public void removeVideoByCourseId(String courseId) {
        // 查询该课程的所有小节视频id
        LambdaQueryWrapper<EduVideo> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(EduVideo::getVideoSourceId)
                .eq(EduVideo::getCourseId, courseId);
        List<Object> objs = videoMapper.selectObjs(wrapper);
        if (objs != null) {// 说明该课程有小节
            // 远程调用视频服务删除视频(遍历)
            for (int i = 0; i < objs.size(); i++) {
                String videoId = (String)objs.get(i);
                if (StringUtils.isNotBlank(videoId)){
                    R result = feignService.removeVideoById(videoId);
                    if (20001 == result.getCode()){
                        throw new GuliException(20001, result.getMessage());
                    }
                }
            }
            // 删除小节信息
            videoMapper.delete(new LambdaQueryWrapper<EduVideo>().eq(EduVideo::getCourseId, courseId));
        }
    }

    /**
     * 根据小节id，删除小节信息
     * @param videoId
     */
    @Override
    public void removeVideoById(String videoId) {
        // 1 查询小节视频的id
        LambdaQueryWrapper<EduVideo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(EduVideo::getId, videoId);
        EduVideo eduVideo = videoMapper.selectById(videoId);
        if (StringUtils.isNotBlank(eduVideo.getVideoSourceId())){
            // 2 删除小节视频
            R result = feignService.removeVideoById(eduVideo.getVideoSourceId());
            if (20001 == result.getCode()){
                throw new GuliException(20001, result.getMessage());
            }
        }
        // 3 删除小节信息
        videoMapper.deleteById(videoId);
    }
}
